﻿using System;
using System.Net;
using System.Text;
using System.Windows;
using eLearning.Model;
using eLearning.Util;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using Newtonsoft.Json;
using System.Windows.Media.Imaging;

namespace eLearning.View
{
    public partial class PengumumanDetailPage : PhoneApplicationPage
    {
        private object data = null;
        private PengumumanList announce;
        private PengumumanMatkulList announceMatkul;

        public PengumumanDetailPage()
        {
            InitializeComponent();
            this.Loaded += new RoutedEventHandler(RssItemPage_Loaded);
        }

        private void RssItemPage_Loaded(object sender, RoutedEventArgs e)
        {
            data = DataContext;
            if (data != null)
            {
                FindPengumumanById(data);                
            }
            ManageButton();
        }
        
        private void FindPengumumanById(object data)
        {
            string url = null, json = null;

            if (data != null && data is Pengumuman)
            {
                Pengumuman pengumuman = (Pengumuman)data;
                if (pengumuman != null)
                {
                    url = Config.Instance.ANNOUNCE_SERVICE_URL() + Config.VIEW_ACTION_KEY;
                    json = JsonConvert.SerializeObject(pengumuman);
                }
            }
            else if (data != null && data is PengumumanMatkul)
            {
                PengumumanMatkul pengumuman = (PengumumanMatkul)data;
                if (pengumuman != null)
                {
                    url = Config.Instance.ANNOUNCE_M_SERVICE_URL() + Config.VIEW_ACTION_KEY + "Detail";
                    json = JsonConvert.SerializeObject(pengumuman);
                }
            }

            Uri uri = new Uri(url, UriKind.Absolute);
            WebClient client = new WebClient();

            client.Encoding = Encoding.UTF8;
            client.Headers[HttpRequestHeader.ContentType] = "application/json";
            client.Headers[HttpRequestHeader.ContentLength] = json.Length.ToString();

            client.UploadStringCompleted += new UploadStringCompletedEventHandler(findAnnouncement_UploadStringCompleted);
            client.UploadStringAsync(uri, "POST", json);
        }

        private void findAnnouncement_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
        {
            try
            {
                if (data is Pengumuman)
                {
                    announce = JsonConvert.DeserializeObject<PengumumanList>(e.Result);
                    textBoxCreated.Text = Utility.nullToEmpty(announce[0].Created.ToString());
                    textBoxCreator.Text = Utility.nullToEmpty(announce[0].Creator.Nama);
                    textBoxPerihal.Text = Utility.nullToEmpty(announce[0].Perihal);
                    textBoxPengumuman.Text = Utility.nullToEmpty(announce[0].Info);
                    imagePengumuman.Source = string.IsNullOrEmpty(announce[0].ImageUrl) ? null : new BitmapImage(new Uri(announce[0].ImageUrl));
                }
                else if (data is PengumumanMatkul)
                {
                    announceMatkul = JsonConvert.DeserializeObject<PengumumanMatkulList>(e.Result);
                    textBoxCreated.Text = Utility.nullToEmpty(announceMatkul[0].Created.ToString());
                    textBoxCreator.Text = Utility.nullToEmpty(announceMatkul[0].DetMatkul.Creator.Nama);
                    textBoxPerihal.Text = Utility.nullToEmpty(announceMatkul[0].Perihal);
                    textBoxPengumuman.Text = Utility.nullToEmpty(announceMatkul[0].Info);
                    imagePengumuman.Source = string.IsNullOrEmpty(announceMatkul[0].ImageUrl) ? null : new BitmapImage(new Uri(announceMatkul[0].ImageUrl));
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("ERROR : " + ex.Message);
            }
        }

        private void editButton_Click(object sender, System.EventArgs e)
        {
            if (data is Pengumuman)
            {
                Utility.GotoPage(this, "/View/PengumumanFormPage.xaml");
            }
            else
            {
                Utility.GotoPage(this, "/View/PengumumanMatkulFormPage.xaml");
            }
            FrameworkElement root = Application.Current.RootVisual as FrameworkElement;
            root.DataContext = data;
        }

        private void removeButton_Click(object sender, System.EventArgs e)
        {
            if (MessageBox.Show("Remove this record?", "", MessageBoxButton.OKCancel) == MessageBoxResult.OK)
                DeleteCurrentAnnounce();
        }

        private void DeleteCurrentAnnounce()
        {
            string json = null, url = null;

            if (data is Pengumuman)
            {
                Pengumuman pengumuman = (Pengumuman)data;
                url = Config.Instance.ANNOUNCE_SERVICE_URL() + Config.DELETE_ACTION_KEY;      
                json = JsonConvert.SerializeObject(pengumuman);
            }
            else if (data is PengumumanMatkul)
            {
                PengumumanMatkul pengumuman = (PengumumanMatkul)data;
                url = Config.Instance.ANNOUNCE_M_SERVICE_URL() + Config.DELETE_ACTION_KEY;                
                json = JsonConvert.SerializeObject(pengumuman);
            }

            Uri uri = new Uri(url, UriKind.Absolute);
            WebClient client = new WebClient();

            client.Encoding = Encoding.UTF8;
            client.Headers[HttpRequestHeader.ContentType] = "application/json";
            client.Headers[HttpRequestHeader.ContentLength] = json.Length.ToString();

            client.UploadStringCompleted += new UploadStringCompletedEventHandler(deleteAnnouncement_UploadStringCompleted);

            try
            {
                client.UploadStringAsync(uri, "POST", json);
            }
            catch (Exception) { }
        }

        private void deleteAnnouncement_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
        {
            try
            {
                if (e.Cancelled && e.Error != null)
                    return;

                MessageBox.Show("Message : " + e.Result);
                if (e.Result.Contains("Success"))
                    NavigationService.GoBack();

            }
            catch (Exception ex)
            {
                MessageBox.Show("ERROR : " + ex.Message);
            }
        }

        private void ManageButton()
        {
            if (SavedUser.Instance.User != null && data != null &&
                (SavedUser.Instance.User.Type == User.UserType.Dosen || SavedUser.Instance.User.Type == User.UserType.Admin))
            {
                ((ApplicationBarIconButton)ApplicationBar.Buttons[0]).IsEnabled = true;
                ((ApplicationBarIconButton)ApplicationBar.Buttons[1]).IsEnabled = true;
            }
            else
            {
                ((ApplicationBarIconButton)ApplicationBar.Buttons[0]).IsEnabled = false;
                ((ApplicationBarIconButton)ApplicationBar.Buttons[1]).IsEnabled = false;
            }
        }

        private void cancelButton_Click(object sender, EventArgs e)
        {
            NavigationService.GoBack();
        }

    }
}